package com.herench.bunch.clinic.convert;

import ca.uhn.hl7v2.model.GenericComposite;
import ca.uhn.hl7v2.model.GenericPrimitive;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.Varies;
import ca.uhn.hl7v2.model.v24.datatype.CE;
import ca.uhn.hl7v2.model.v24.group.RTB_K13_ROW_DEFINITION;
import ca.uhn.hl7v2.model.v24.message.QBP_Q11;
import ca.uhn.hl7v2.model.v24.message.QRY_Q01;
import ca.uhn.hl7v2.model.v24.message.RTB_K13;
import ca.uhn.hl7v2.model.v24.segment.MSA;
import ca.uhn.hl7v2.model.v24.segment.MSH;
import ca.uhn.hl7v2.model.v24.segment.RDT;
import ca.uhn.hl7v2.parser.DefaultModelClassFactory;
import com.alibaba.fastjson.JSON;
import com.herench.bunch.clinic.handler.ProxyMsgCodeConstant;
import com.herench.bunch.clinic.support.ProxyMsgTemplate;
import com.herench.bunch.commons.support.RequestMessage;
import org.dom4j.Document;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.List;
import java.util.Map;

public class CheckBillConvert extends AbstractMessageConvert {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public Document doToMessage(RequestMessage requestMessage) throws Exception {
        Document document = ProxyMsgTemplate.getInMsgTpl(ProxyMsgCodeConstant.DOCTOR_INFORMATION_TRADE_CODE);
        Element requestElement = document.getRootElement();
        QBP_Q11 hl7 = (QBP_Q11) requestMessage.getHl7Message();
        GenericComposite gc = (GenericComposite) hl7.getQPD().getQpd3_UserParametersInsuccessivefields().getData();
        if (gc != null) {
            Varies varies = (Varies) gc.getComponent(1);
            if (varies != null) {
                GenericPrimitive primitive = (GenericPrimitive) varies.getData();
                String qpdString = primitive.getValue();
                String[] qpds = qpdString.split("#");
                if (qpds.length < 2) {
                    throw new RuntimeException("缺少必要参数");
                }
                for (String qpd : qpds) {
                    String[] temp = qpd.split("=");
                    if(temp.length>1){
                        requestElement.addElement(temp[0]).addText(temp[1] != null ? temp[1] : "");
                    }else {
                        requestElement.addElement(temp[0]).addText("");
                    }
                }
            }
        }
        String res = document.asXML();
        logger.info(requestMessage.getMsgCode() + " to HIS XML = "+ res);
        return document;
    }

    @Override
    public Message doFromMessage(String message) throws Exception {
        Assert.notNull(message, "message 为空");
        logger.info("200250 message = "+ message);
        List<Map<String,Object>> resList = (List<Map<String, Object>>) JSON.parse(message);

        RTB_K13 rtbK13 = new RTB_K13();
        rtbK13.initQuickstart("RTB_K13", "RTB_K13", "P");
        MSH msh = rtbK13.getMSH();
        initResponseMessageMSH(msh);
        MSA msa = rtbK13.getMSA();
        if (resList.size()>0){
            msa.getErrorCondition().getCe1_Identifier().setValue("1");
            msa.getErrorCondition().getCe2_Text().setValue("成功");
        }else {
            msa.getErrorCondition().getCe1_Identifier().setValue("0");
            msa.getErrorCondition().getCe2_Text().setValue("无数据");
        }

        RTB_K13_ROW_DEFINITION definition = rtbK13.getROW_DEFINITION();
//        Element items = doc.getRootElement().element("Items");
//
        int index = 0;
//        for (Iterator<Element> iterator = items.elementIterator(); iterator.hasNext(); ) {
//            Element el = iterator.next();
        for (int i = 0;i<resList.size();i++){
            RDT rdt = new RDT(rtbK13, new DefaultModelClassFactory());
            CE ce = new CE(rtbK13);
            ce.getCe1_Identifier().setValue("RD");
            StringBuffer buffer = new StringBuffer();
            buffer.append("divisionId=").append(resList.get(i).get("divisionId")).append("#")
                    .append("orderState=").append(resList.get(i).get("orderState")).append("#")
                    .append("payTotalAmount=").append(resList.get(i).get("payTotalAmount")).append("#")
                    .append("settlementType=").append(resList.get(i).get("settlementType")).append("#")
                    .append("tradeDateTime=").append(resList.get(i).get("tradeDateTime")).append("#")
                    .append("payType=").append(resList.get(i).get("payType")).append("#")
                    .append("payBusinessType=").append(resList.get(i).get("payBusinessType")).append("#")
                    .append("patType=").append(resList.get(i).get("patType")).append("#")
                    .append("patientCardNo=").append(resList.get(i).get("patientCardNo")).append("#")
                    .append("patientName=").append(resList.get(i).get("patientName")).append("#")
                    .append("cashier=").append(resList.get(i).get("cashier")).append("#")
                    .append("orderNo=").append(resList.get(i).get("orderNo"));

            ce.getCe2_Text().setValue(buffer.toString());
            rdt.getColumnValue().setData(ce);
            definition.insertRDT(rdt, index++);
        }
        return rtbK13;
    }



    @Override
    public Message generatorReqMessage() throws Exception {
        QRY_Q01 qryQ01 = new QRY_Q01();
        qryQ01.initQuickstart("QRY_Q01", "QRY_Q01", "A");


        return null;
    }
}
